<?php

/*
 * This file is part of the znmin/deployer.
 *
 * (c) jimmy.xie <jimmy.xie@znmin.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Deployer;

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

class Deployer
{
    protected $username;

    protected $password;

    protected $branch;

    protected $deploy_path;

    protected $process;

    public function __construct($username, $password, $branch, $deploy_path = '')
    {
        $this->username = $username;
        $this->password = $password;
        $this->branch = $branch;
        $this->deploy_path = $deploy_path;
    }

    /**
     * 执行部署.
     *
     * @throws DeployerException
     */
    public function run()
    {
        $username = $this->username;
        $deploy_path = $this->getDeployPath();
        $branch = $this->branch;

        $center = <<<EOF
echo 'expect "$username" {send "cd $deploy_path \\r"}' >> \$FILE
echo 'expect "$deploy_path" {send "git pull origin $branch \\r"}' >> \$FILE
echo 'expect "git pull origin"' >> \$FILE

EOF;

        $process = $this->buildProcess($center);
        $process->run();

        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }
    }

    /**
     * 生成进程对象
     *
     * @param $center_commandline
     *
     * @return Process
     *
     * @throws DeployerException
     */
    protected function buildProcess($center_commandline)
    {
        return Process::fromShellCommandline(
            $this->buildCommandline($center_commandline)
        );
    }

    /**
     * 生成部署命令.
     *
     * @return string
     *
     * @throws DeployerException
     */
    protected function buildCommandline($center_commandline)
    {
        return $this->buildHeader().$center_commandline.$this->buildFooter();
    }

    protected function buildHeader()
    {
        $username = $this->username;

        $password = $this->password;

        return <<<EOF
FILE='/tmp/.login.sh'
echo '#!/usr/bin/expect -f' > \$FILE
echo 'set timeout 30' >> \$FILE
echo 'spawn su - $username' >> \$FILE
echo 'expect "*Password:" {send "$password\\r"} ' >> \$FILE

EOF;
    }

    protected function buildFooter()
    {
        return <<<'EOF'
echo 'interact' >> $FILE
chmod a+x $FILE
$FILE

EOF;
    }

    /**
     * 获取工作空间.
     *
     * @return false|string
     *
     * @throws DeployerException
     */
    protected function getDeployPath()
    {
        if ($this->deploy_path) {
            return $this->deploy_path;
        }

        do {
            $path = realpath(($path ?? __DIR__).'/../');

            if ('/' == $path) {
                throw new DeployerException('Workspace not found');
            }
        } while (!file_exists($path.'/.git'));

        return $path;
    }
}
